package com.example.ggpicturegg.tool;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.wifi.aware.DiscoverySession;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import com.example.ggpicturegg.Mysql_com.ImageInfo;

public class Loaddata {

    private static String Tag= "http://159.75.6.220:888/";
    private static Handler mainHandler;

    public static Bitmap getImage(String path,int id){
        path = Tag+"No."+id+"-"+path;
       // System.out.println("   "+id+" ----------------- path ---------------is   " + path);
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
          //  System.out.println("----------------- 加载数据 ---------------");
            if(conn.getResponseCode() == 200){
                InputStream inputStream = conn.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
             //   System.out.println("-----------------  bitmap is ok ---------------");
                return bitmap;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
        return null;
    }


    public static List<ImageInfo> getBitmap(List<ImageInfo> list){


        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i =0;i<list.size();i++){
                    Bitmap bitmap =  Loaddata.getImage(list.get(i).getPicture_name(),list.get(i).getId());
                    Message message = new Message();
                    message.what = 0 ;
                    message.arg1 = i ;
                    message.obj = bitmap;
                    mainHandler.sendMessage(message);
                }

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }).start();


        mainHandler = new Handler(Looper.myLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);

                if(msg.what == 0){
                    Bitmap bitmap = (Bitmap)msg.obj;
                    int i = msg.arg1;
                    list.get(i).setBitmap(bitmap);
                }
            }
        };
        return list;
    }
}
